from django import template
from django.db.models import Count
from lxml import etree
from .. import inc 
from core.models import *
import json
import os

register = template.Library()
def do_select(parser,token):
  nodelist = parser.parse('endselect')
  parser.delete_first_token()
  return SelectNode(nodelist)

class SelectNode(template.Node):
  def __init__(self,nodelist):
    self.nodelist = nodelist
  def render(self,context):
    data_str = self.nodelist.render(context)
    data = json.loads(data_str)
    default = "NIL"
    dstr = ""
    if(data.has_key('default')):
      default = data['default']
      dstr = default 
    rend_result = """\
<div class="extension-drop-list" style="%s">\
<input type="textfield" style="display:none" name="%s" value="%s"></input>\
<div class='current'>%s</div><ul>"""\
    % (data['style'],data['name'],dstr,default)
    for field in data['fields']:
      if (field == default):
        rend_result += "<li><h5>"+field+"</h5><span style='font-size:16px'>&#9746</span></li>"
      else:
        rend_result += "<li><h5>"+field+"</h5><span style='font-size:16px'>&#9744</span></li>"
    tail = """</ul></div>"""
    return rend_result+tail

register.tag("select",do_select)

class ComboRender:
  def __init__(self, name):
    self.name = name
    self.style = ""
    self.fields = []
    self.nation = ""

  def Render(self):
    nation_items = self.nation.split(",")
    rend_result = """\
<div class="extension-combo-select" style="%s">\
<input type="textfield" style="display: none" name="%s" value="%s"/>\
<div class='current'>MIXED</div><ul><li id='selectall'><h5>Select all</h5><span></span></li><li id='deselectall'><h5>Deselect all</h5><span></span></li>"""\
    % (self.style, self.name, self.nation)

    # change by mike for display the selected items
    for field in self.fields:
      f = 0
      for n in nation_items:
        if n == field:
          f = 1
      if f == 1:
        rend_result += "<li><h5>" + field + "</h5><span style='font-size:16px'>&#9746;</span></li>"
      else:
        rend_result += "<li><h5>" + field + "</h5><span style='font-size:16px'>&#9744;</span></li>"

    tail = """</ul></div>"""
    return rend_result + tail
  def AddField(self, field_name):
    self.fields.append(field_name)
  def SetStyle(self, style):
    self.style = style
  def SetNationList(self,nationlist):
    self.nation = nationlist 

class DictRender:
  def __init__(self,name):
    self.name = name
    self.style = ""
    self.dictionary = {}
  def Render(self):
    rend_result = """\
<div class='extension-dict-select' style='%s'>\
<input type='textfield' style='display:none' name='%s' />\
<div class='current'>NIL</div><ul class='key'>"""\
    % (self.style,self.name)
    for k in self.dictionary.keys():
      rend_result += "<li class='key'><span class='key'>" + k  + "</span><ul class='item'>"
      for v in self.dictionary[k]:
        rend_result += "<li class='item'><h5>" + v + "</h5></li>"
      rend_result += "</ul></li>"
    rend_result += "</ul>"
    rend_result += "</div>"
    return rend_result
  def SetStyle(self,style):
    self.style = style
  def AddField(self,dic):
    self.dictionary = dic

class AutoCompleteRender:
  def __init__(self, name):
    self.name = name
    self.style = ""
    self.call_back = ""
    self.fields = []
  def Render(self):
    rend_result = """\
<div class="extension-auto-complete" style="%s">\
<!--call_back:%s-->\
<input type="textfield" name="%s" onkeypress="pressEnter(event)"/>\
<div class="autocomp-drop-list"><ul class="hint"></ul>\
</div>\
</div>"""\
    % (self.style,self.call_back,self.name)
    return rend_result
  def SetStyle(self, style):
    self.style = style
  def SetCallBack(self,cb):
    self.call_back = cb

@register.filter("component")
def component(template,comp):
  return "comp/"+template+"/_"+comp+".html" 



@register.filter("auto_complete")
def auto_complete(acname):
  return AutoCompleteRender(acname)

@register.filter("combo")
def combo(comboname):
  return ComboRender(comboname)

@register.filter("dictionary")
def dictionary(name):
  return DictRender(name)

@register.filter("post")
def post(pname,sname):
  f = open(inc.CONFIG.SERVICES_PATH + sname+'/' + pname + '.post',"r")
  buf = f.read()
  f.close()
  return buf

@register.filter("template")
def template(cname):
  return "comp/_"+cname+".html"

@register.filter("style")
def style(ele_config,style):
  ele_config.SetStyle(style)
  return ele_config

@register.filter("addfield")
def addfield(ele_config,field):
  ele_config.AddField(field)
  return ele_config

@register.filter("serviceNation")
def serviceNation(ele_config,nationlist):
  ele_config.SetNationList(nationlist)
  return ele_config

@register.filter("callback")
def callback(ele_config,cb):
  ele_config.SetCallBack(cb)
  return ele_config
 
@register.filter("render")
def render(ele_config):
  return ele_config.Render()

@register.filter("xslt")
def xslt(xslt,item):
  str = etree.tostring(xslt(item.getroot())).replace('</span></td></tr><tr><td><label>age:</label></td><td><span>','</span></td></tr><tr style="display:none"><td><label>age:</label></td><td><span>')
  str = str.replace('nationality:','from:');
  return str

@register.filter("info")
def info(inf):
  item = etree.fromstring(inf.data)
  attributes = item.attrib
  description = item.xpath("string()")
  return {'TEXT':description,'ATTRS':attributes}

@register.simple_tag
def xattr(item,path):
  if item:
    return item.xpath(path)[0]
  else:
    return "None"

@register.simple_tag
def typetags(name):
  tag_agg = ServiceCore.objects.values('type').annotate(count=Count('type'))
  total = 0
  outdiv = "<div class='extension-tag-list'><input name='" + name + "' value='all'></input>"
  list = ""
  for tag in tag_agg:
    list += "<li><h5>"+tag['type']+"</h5><span onclick=\"zoyoe.search.TargetType('"
    list += tag['type'] + "',false)\">"+str(tag['count'])+"</span></li>";
    total += tag['count']
  list = "<ul class='type-tags'><li><h5>all</h5><span>"+str(total) + "</span></li>" + list
  list += "<br style='clear:both'/></ul>"
  return outdiv + list + "</div>"

@register.simple_tag
def localtags(name):
  tag_agg = ServiceCore.objects.values('local').annotate(count=Count('type'))
  total = 0
  outdiv = "<div class='extension-tag-list'><input name='" + name + "' value='all'></input>"
  list = ""
  for tag in tag_agg:
    list += "<li><h5>"+tag['local']+"</h5><span onclick=\"zoyoe.search.TargetLocation('"
    list += tag['local'] + "',false)\">"+str(tag['count'])+"</span></li>";
    total += tag['count']
  list = "<ul class='type-tags'><li><h5>all</h5><span>"+str(total) + "</span></li>" + list
  list += "<br style='clear:both'/></ul>"
  return outdiv + list + "</div>"

@register.simple_tag
def zoyoejs(arg):
  return """\
  <script src="http://yui.yahooapis.com/3.4.1/build/yui/yui-min.js"></script> \
  <script type="text/javascript" src="/js/ui.js"></script>    \
  <script type="text/javascript" src="/js/comps.js"></script> \
  <script type="text/javascript" src="/js/zoyoe.js"></script> \
  <script type="text/javascript" src="/js/ele.js"></script>"""

@register.simple_tag
def isUserAuth(user, service):
  if (str(user) == 'AnonymousUser'):
    return "false";
  elif (str(user) == 'SYSTEM'):
    return "true";
  else:
    try:
      service_data = ServiceCore.objects.get(name = str(service.name))
      if (service_data.email == str(user.email)):
        return "true";
      else:
        return "false";
    except ServiceCore.DoesNotExist:
      return "false";

''' by mike 20121106 '''
@register.filter("modulo")
def  modulo(data):
  return data % 2

@register.filter("totalele")
def  totalele(data):
  return len(data)
